<?PHP
require_once('config.inc.php');
require_once('database.inc.php');
require_once('functions.inc.php');
require_once(LIBRARY_PATH.'json/JSON.php');
require('security.php');

$db = LinkDB();
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);

//解析数据
$valuePack = $json->decode(getJsonString($_POST['data']));
if (!$valuePack) feedback(false, '数据解析失败');

//获取当前系统时间
$actionDate = date('Y-m-d H:i:s');

//处理数据
switch ($valuePack['action']) {
	case 'create':
		if (!findPopedom('linkman', 'create')) feedback(false, '[没有进行此操作的权限]');
		creatLinkMan($valuePack);
		break;
	case 'edit':
		if (!findPopedom('linkman', 'edit')) feedback(false, '[没有进行此操作的权限]');
		editLinkMan($valuePack);
		break;
	case 'delete':
		if (!findPopedom('linkman', 'delete')) feedback(false, '[没有进行此操作的权限]');
		deleteLinkMan($valuePack);
		break;
	default:
		feedback(false, '[未定义的操作]');
		break;
}

//创建联系人
function creatLinkMan($valuePack) {
	$basicData = $valuePack['basicData'];
	global $db, $actionDate;
	$basicData['created'] = $actionDate;
	$basicData['dataversion'] = SYSTEM_VERSION;
	if (InsertData($db, 'people', $basicData)) {
		feedback(true, '已经成功创建新联系人');
	}else {
		feedback(false, '[数据库错误]'.$db->ErrorMsg());
	}
}

//编辑联系人
function editLinkMan($valuePack) {
	$basicData = $valuePack['basicData'];
	$basicData = setEmptyToNull($basicData);
	$id = (int)$basicData['id'];
	global $db, $actionDate;
	$basicData['updated'] = $actionDate;
	$basicData['brief'] = '';
	$briefArray = array_merge($valuePack['customData']['update'], $valuePack['customData']['create']);
	foreach($briefArray as $item) {
		$addString = ($basicData['brief'] ? ' / ' : '').$item['name'].':'.$item['content'];
		if (strlen($addString) + strlen($basicData['brief']) > 255) break;
		$basicData['brief'] .= $addString;
	}
	$basicData['dataversion'] = SYSTEM_VERSION;
	if (!UpdateData($db, 'people', $basicData, 'id = '.$id) && $db->ErrorMsg()) {
		feedback(false, '[数据库错误,无法更新联系人基本信息]'.$db->ErrorMsg());
	}
	$results = array();
	foreach ($valuePack['customData'] as $action=>$data) {
		switch ($action) {
			case 'create':
				$results[$action] = createCustomItem($data, $id);
				break;
			case 'update':
				$results[$action] = updateCustomItem($data);
				break;
			case 'delete':
				$results[$action] = deleteCustomItem($data);
				break;
		}
	}
	$allSucceed = true;
	$messageString = '';
	foreach ($results as $key=>$result) {
		if (count($result['failed'])) {
			$allSucceed = false;
			$messageString .= $key;
			foreach ($result['failed'] as $failedMessage) {
				$messageString .= '['.$failedMessage.']';
			}
		}
	}
	if (!$allSucceed) {
		feedback(false, $messageString);
	}else {
		feedback(true, '联系人修改成功');
	}
}

/**
 * 新建自定义项目
 *
 * @param array $dataPack 自定义项目数据包数组
 * @return array 装载结果信息的数组，“succeed”为成功数量，“failed”为失败数量
 */
function createCustomItem($dataPack, $fatherid) {
	$result = array(
		'succeed'=> 0,
		'failed' => array()
	);
	global $db, $actionDate;
	foreach ($dataPack as $valuePack) {
		$valuePack['created'] = $actionDate;
		$valuePack['fatherid'] = $fatherid;
		$valuePack['dataversion'] = SYSTEM_VERSION;
		if (InsertData($db, 'contactinfo', $valuePack)) {
			$result['succeed']++;
		}else {
			$result['failed'][] = $db->ErrorMsg();
		}
	}
	return $result;
}

/**
 * 修改自定义项目
 *
 * @param array $dataPack 自定义项目数据包数组
 * @return array 装载结果信息的数组，“succeed”为成功数量，“failed”为失败数量
 */
function updateCustomItem($dataPack) {
	$result = array(
		'succeed'=> 0,
		'failed' => array()
	);
	global $db, $actionDate;
	foreach ($dataPack as $valuePack) {
		$valuePack['updated'] = $actionDate;
		$valuePack['dataversion'] = SYSTEM_VERSION;
		if (updateData($db, 'contactinfo', $valuePack, 'id = '.(int)$valuePack['id']) || !$db->ErrorMsg()) {
			$result['succeed']++;
		}else {
			$result['failed'][] = $db->ErrorMsg();
		}
	}
	return $result;
}

/**
 * 删除自定义项目
 *
 * @param array $dataPack 自定义项目数据包数组
 * @return array 装载结果信息的数组，“succeed”为成功数量，“failed”为失败数量
 */
function deleteCustomItem($valuePack) {
	$result = array(
		'succeed'=> 0,
		'failed' => array()
	);
	global $db;
	foreach ($valuePack as $id) {
		if (deleteData($db, 'contactinfo', 'id = '.(int)$id)) {
			$result['succeed']++;
		}else {
			$result['failed'][] = $db->ErrorMsg();
		}
	}
	return $result;
}

//删除联系人
function deleteLinkMan($valuePack) {
	$id = (int)$valuePack['id'];
	global $db;
	if (deleteData($db, 'contactinfo', 'fatherid = '.$id)) {
		if (DeleteData($db, 'people', 'id = '.$id)) {
			feedback(true, '已经成功删除联系人');
		}else {
			feedback(false, '[删除联系人失败,数据库错误]'.$db->ErrorMsg());
		}
	}else {
		feedback(false, '[删除联系人详细信息失败,数据库错误]'.$db->ErrorMsg());
	}
}

/**
 * 将数组中内容为空字符串的元素内容转换为'null'
 *
 * @param array $array 原始数组
 * @return array
 */
function setEmptyToNull($array) {
	foreach ($array as $key=>$value) {
		if ($value === '') $array[$key]='null';
	}
	return $array;
}
?>